const App = getApp()
const util = require('../../../utils/util.js')
Page({
  data: {
    billType: 0,
    orderType: '',
    desc: '',
    date: '',
    time: '',
    lock: true,
    checked: false,
    totalAmount: '', // 实际支付
    total: '', // 合计
    intMoney: 0,
    intVal: '',
    userInfo: {
      discount: 0, // 用户优惠金额 
      heavydiscount: '', //大客户优惠金额
      heavydiscountType: '', //大客户折扣类型
      linkman: '', // 联系人 
      phone: '', // 联系电话 
      appointmentTime: '', // 预约时间
      fullCuts: [], //满减活动
    },
    //满减活动
    fullcut: {
      cash: 0, //优惠金额
      fullCutInfo: '', //优惠信息：比如：满5.00块减1.00元
      fullCutTime: '', //活动剩余天数：比如：剩余14天结束
      meet: 0, //花费金额：比如：5.00元
      postage: 0, //邮费
    },
    status: 0,
    status2: 0,
    png: false,
    showInvoice: false,
    showIntegral: false,
    couponsList: [],
    coupons: '',
    couponsFee: 0,
    couponsId: 0,
    billId: 0,
    discounts: 0
  },
  onLoad(option) {

    
    //请求有无机会抽奖
     var   params={}
    params.sellerId =  wx.getStorageSync('agent').id,



    App.HttpService.gongshifei(params).then(res => {
      console.log(res, "请求是否跳转抽奖")
      this.setData({
        gongshifei:res.data.data.hourFee,
        status: res.data.data.status

      })

    
    })







    this.setData({
      gsf: JSON.parse(wx.getStorageSync('gsfid'))
    })



    let defaultCar = wx.getStorageSync('defaultCar');
    let products = wx.getStorageSync('products');
    let userId = wx.getStorageSync('userId');
    let agent = wx.getStorageSync('agent');
    let goodsInfo = [];
    let intMoney = 0;
    let nowDate = new Date().getTime();
    products.forEach(item => {
      item.pricetotal = (Number(item.price) * item.num).toFixed(2)
      goodsInfo.push({
        goodsId: item.id,
        num: item.num
      })
    })
    this.setData({
      merchant: option,
      defaultCar,
      products,
      goodsInfo,
      userId,
      agent,
      'userInfo.carCode': defaultCar.carCode,
      'userInfo.linkman': defaultCar.linkman,
      'userInfo.phone': defaultCar.phone,
      'userInfo.appointmentTime': option.date + ' ' + option.time,
      intMoney: intMoney.toFixed(2),
      xianshi: wx.getStorageSync('isShareActivity')
    })
    this.discount()
    this.userInfo()
  },
  onShow() {
    let billType = parseInt(wx.getStorageSync('billTypeId'));
    if (!billType) {
      billType = 0;
    }
    this.setData({
      billType,
      billId: billType
    });

  },
  discount() { // 优惠活动
    let {
      userId,
      agent
    } = this.data
    let params = {
      buyerId: userId,
      sellerId: agent.id,
      type: 0
    }
    App.HttpService.discount(params).then(res => {
      let data = res.data.data
      // debugger
      if (res.data.code == 200) {
        //判断是否满足大客户折扣
        if (data.isdiscount == 1) {
          // debugger
          this.setData({
            'userInfo.heavydiscount': data.discountValue,
            'userInfo.heavydiscountType': data.discountType,
          })

        }
        //判断用户状态，与代理商状态,是否满足首单立减
        if (data.buyerStatus == 1 && data.sellerStatus == 1) {
          this.setData({
            'userInfo.discount': data.sellerValue
          })
        }

        //查询是否存在满减活动


        if (data.fullCut.length > 0) {

          let fullCuts = [];
          data.fullCut.forEach(item => {
            //判断符合当前订单金额的满减活动
            fullCuts.push(item);

          });
          this.setData({
            'userInfo.fullCuts': fullCuts
          })

          console.log(this.data.userInfo.fullCuts);
        }
        this.calAmount()
      }
    })
  },
  userInfo() { // 获取积分
    let {
      userId
    } = this.data
    App.HttpService.userInfo({
      userId: userId
    }).then(res => {
      let data = res.data
      let k = data.data.consumeInfo.countsValue
      let d = data.data.consumeInfo.coinValue
      let s = data.data.userInfo.score


      if (k && d && s) {
        console.log("有")
        this.setData({
          xian: true,
          jifen: s,
          cs: d,
          bcs: k
        })
      } else {
        this.setData({
          xian: false
        })
        console.log("无")
      }

      if (data.code == 200) {
        let integral = data.data.consumeInfo
        integral.score = data.data.userInfo.score
        this.setData({
          integral: integral
        })
      }
    })
  },
  calAmount() { //计算总价格

    var bu = this.data.gsf.money
    if (bu) {
      var uj = bu
    } else {
      var uj = 0
    }
  

    let {
      userInfo,
      products
    } = this.data
    let total = 0 + uj
    products.forEach(item => {
      total += item.price
    })

    //判断大客户优惠
    let temp_heavydiscount = 0;
    if (userInfo.heavydiscountType == 0) {
      temp_heavydiscount = total * userInfo.heavydiscount / 100;
    } else {
      temp_heavydiscount = userInfo.heavydiscount;
    }
    total = total - temp_heavydiscount;
    //定义满减金额值是否有满足
    let fullcuts = [] = this.data.userInfo.fullCuts
    let cash = 0;
    let temp = 0;
    fullcuts.forEach(item => {
      if (item.meet <= total) {
        if (item.meet >= temp) {
          temp = item.meet;
          cash = item.cash;
          this.setData({
            'fullcut.fullCutInfo': item.fullCutInfo,
            'fullcut.fullCutTime': item.fullCutTime
          })
        }
      }
    });
    total = total - cash;
    this.setData({
      discounts: userInfo.discount + temp_heavydiscount + cash
    })
    //总金额减去首单立减
    total = total - userInfo.discount;
    total = total.toFixed(2);
    //如果优惠活动大于支付金额则支付0.01
    if (total < 0) {
      total = 0.01
    }
    this.setData({
      total,
      totalAmount: total,

      chang: total


    })
    // 查询优惠券个数
    this.chaxunyouhuiquan();
  },
  // 计算出最后支付的价格
  calTotalAmount() {
    let {
      totalAmount,
      total,
      couponsFee,
      intMoney
    } = this.data;
    totalAmount = total - couponsFee - intMoney;
    totalAmount = totalAmount.toFixed(2)


    // 如果最后计算金额等于0 赋值0.01
    if (totalAmount <= 0) {
      this.setData({
        totalAmount: 0.01

      })

    } else {

      this.setData({
        totalAmount
      });
    }
  },

  bzxx: function(e) {
    console.log(e.detail.value)
    this.setData({
      beizhu: e.detail.value
    })
  },

  inputBlur(e) { // 失去焦点时间
    let {
      key
    } = e.currentTarget.dataset
    let {
      value
    } = e.detail
    this.setData({
      [key]: value
    })
  },
  bindTextAreaBlur(e) { // 监听到新输入的值
    this.setData({
      desc: e.detail.value
    })
  },
  integralBlur(e) {

    //积分
    var j = this.data.jifen
    // 总金额  *被除数/除数 =  最大可输入积分数
    var l = this.data.chang * (this.data.bcs / this.data.cs)
    if (j > l) {
      var g = l
    } else {
      var g = j
    }
    console.log(g)
    let {
      value
    } = e.detail
    this.setData({
      value
    })

    if (value > g) {
      value = g
      this.setData({
        value: g,

      })
      wx.showToast({
        title: "抵扣金额大于总金额",
        icon: 'none',
        duration: 1500
      })
    }

    let integralVal = (Number(value) * (this.data.cs / this.data.bcs)).toFixed(2)


    this.setData({
      //计算好的价格
      intMoney: integralVal,
      intVal: value
    })




    this.calTotalAmount();
  },
  redirectTo(e) {
    App.WxService.redirectTo('/pages/address/confirm/index', {
      ret: this.data.address_id
    })
  },
  addOrder(e) {
    if (!this.data.lock) {
      return false;
    }
    this.setData({
      lock: false
    });
    
    let {
      userInfo,
      date,
      time,
      totalAmount,
      desc,
      goodsInfo,
      agent,
      userId,
      merchant,
      intVal,
      intMoney,
      couponsId,
      billId,
      total
    } = this.data
    if (userInfo.linkman == '') {
      this.alert('请输入联系人')
      return false
    }
    if (userInfo.phone == '') {
      this.alert('请输入联系电话')
      return false
    }
    if (intVal == '') {
      intVal = 0
    }
    let params = {
      buyerId: userId,
      sellerId: agent.id,
      goodsInfo,
      shopId: merchant.merchantId,
      totalAmount,
      total,
      desc,
      userInfo,
      countsValue: intVal,
      countsAmount: intMoney,
      couponsId,
      billId,
      type: 0,
      fromId: e.detail.formId,
      memo: this.data.beizhu,
      gsfid: this.data.gsf.id

    }

    App.HttpService.proOrderSave(params).then(res => {
      let data = res.data
      if (data.code == 200) {
        this.setData({
          lock: true
        });
        let config = data.data
        let prepay_id = e.detail.formId;
        let orderSn = config.orderSn;
        let template_id = 'dqB3ADXmio9LGKUWewpq91fNrFEDd-zn4lDrsRpEiR4';
        let touser = wx.getStorageSync('openid');
        if (config.active) {
          wx.navigateTo({
            url: '/pages/order/list/index?stauts=ALL&back=1'
          })
          wx.removeStorageSync('products')
        } else {
          let payconfig = {
            timeStamp: config.timeStamp,
            nonceStr: config.nonceStr,
            package: config.package,
            signType: config.signType,
            paySign: config.paySign,
            success(res) {
              var params = {
                orderSn: orderSn,

              }
              //请求有无机会抽奖
              App.HttpService.youwuchouj(params).then(res => {
                console.log(res, "请求是否跳转抽奖")
                if (res.data.code == 200) {
                  wx.navigateTo({
                    url: '/pages/choujiang/index',
                  })
                }
              })



            },
          }


          payconfig.fail = () => {

            this.setData({
              lock: true
            });
          }

          wx.requestPayment(payconfig)

        }
      } else {
        wx.showModal({
          title: '提示',
          content: data.msg,
          showCancel: false
        })
        this.setData({
          lock: true
        });
      }
    }, e => {
      wx.showModal({
        title: '提示',
        content: '服务器错误',
        showCancel: false
      })
      this.setData({
        lock: true
      });
    })
  },
  alert(msg) {
    wx.showToast({
      title: msg,
      image: '../../../assets/images/warning.png',
      duration: 1500
    })
  },
  clear() {
    App.HttpService.clearCartByUser().then(res => {
      const data = res.data
    })
  },
  // 跳转到商家
  toMerchant(e) {
    let shopId = e.currentTarget.dataset.id;
    let distance = e.currentTarget.dataset.distance;
    wx.navigateTo({
      url: `/pages/merchantsList/detail/detail?shopId=${shopId}&distance=${distance}`,
    })
  },
  // 购物车详情弹窗
  setModalStatus2(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = !this.data.status;
    this.setData({
      png: !this.data.png
    });
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 1) {
      this.setData({
        showModalStatus2: true
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏购物车弹窗
  setModalStatus3(e) {
 
    let status = 0;
    this.setData({
      png: !this.data.png
    });
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 0) {
      this.setData({
        showModalStatus2: false
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },


  // 查询优惠券
  chaxunyouhuiquan: function() {
    let userId = this.data.userId;
    let amount = this.data.total;
 
    let sellerId = this.data.agent.id;
    App.HttpService.getCoupons({
      userId,
      amount: amount,
      sellerId,
      couponsType: 1
    }).then(res => {
      if (res.data.code == 200) {
        let data = res.data.data;
        this.setData({
          tiaoshu: data.length
        });
      }
    });

  },

  // 优惠券弹窗
  setModalStatus4(e) {
    console.log(e)
    let userId = this.data.userId;
    let amount = this.data.total;
    let sellerId = this.data.agent.id;

    App.HttpService.getCoupons({
      userId,
      amount: amount,
      sellerId,
      couponsType: 1
    }).then(res => {
      if (res.data.code == 200) {
        let data = res.data.data;
        for (let i = 0; i < data.length; i++) {
          if (data[i].id == this.data.coupons) {
            data[i].checked = true;
          } else {
            data[i].checked = false;
          }
        }
        this.setData({
          couponsList: data,
          tiaoshu: data.length
        });

      }
    });
    let status2 = 1;
    this.setData({
      status2
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
    if (status2 == 1) {
      this.setData({
        showModalStatus: true
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status2 == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏优惠券弹窗
  setModalStatus5(e) {

    let status2 = 0;
    this.setData({
      status2
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (status2 == 0) {
      this.setData({
        showModalStatus: false
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (status2 == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 选择优惠券
  chooseCoupons(e) {
    let coupons = e.currentTarget.dataset.id;
    let couponsFee = e.currentTarget.dataset.discountsfee;
    let checkedStatus = e.currentTarget.dataset.checked;
    if (checkedStatus) {
      this.setData({
        coupons: '',
        couponsFee: 0,
        couponsId: 0
      });
    } else {
      this.setData({
        coupons,
        couponsFee,
        couponsId: coupons
      });
    }
    this.setModalStatus5();
    this.calTotalAmount();
    var t = this.data
    this.setData({

      value: '',
      intMoney: 0.00,
      totalAmount: t.total - t.couponsFee,
      chang: t.total - t.couponsFee
    })


  },
  // 是否需要发票
  chooseInvoice(e) {
    this.setData({
      showInvoice: e.detail.value
    });
  },
  // 是否使用积分
  chooseIntegral(e) {
    this.setData({
      showIntegral: e.detail.value
    });
    if (!e.detail.value) {
      this.setData({
        intMoney: 0.00,
        totalAmount: this.data.total - this.data.couponsFee
      });
    }
  },
  // 跳转到发票管理
  toInvoice() {
    wx.navigateTo({
      url: '/pages/invoice/invoice',
    })
  },
  // 监听输入联系人
  linkmanInput(e) {
    this.setData({
      'userInfo.linkman': e.detail.value
    });
  },
  // 监听输入联系电话
  phoneInput(e) {
    this.setData({
      "userInfo.phone": e.detail.value
    });
  }
})